<?php

namespace Common\Bundle\LibraryBundle\Controller;

use Common\Bundle\LibraryBundle\Entity\Evaluation;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Common\Bundle\LibraryBundle\Form\EvaluationType;

/**
 * @Route("/evaluation")
 */
class EvaluationController extends Controller{

    /**
     * @Route("/", options={"expose"=true})
     * @Template()
     */
    public function indexAction()
    {
        $evaluations = $this->getEvaluationRepository()->findAll();
        return array("evaluations" => $evaluations);
    }

    /**
     * @Route("/new", options={"expose"=true}, defaults={"idEvaluation"=null})
     * @Route("/{idEvaluation}/edit", options={"expose"=true})
     * @Template()
     */
    public function editAction($idEvaluation)
    {
        if ($idEvaluation === null) {
            $evaluation = new Evaluation();
        } else {
            $evaluation = $this->getEvaluationRepository()->find($idEvaluation);
        }

        if (!$evaluation) {
            throw $this->createNotFoundException();
        }

        $form = $this->createForm(new EvaluationType(), $evaluation);

        if ($this->getRequest()->isMethod("post")) {
            $form->bind($this->getRequest());
            if ($form->isValid()) {
                $this->getDoctrine()->getManager()->persist($evaluation);
                $this->getDoctrine()->getManager()->flush();
                if($idEvaluation){
                    $this->get('session')->getFlashBag()->add('success', 'Evaluation modifiée');
                }
                else
                {
                    $this->get('session')->getFlashBag()->add('success', 'Evaluation ajoutée');
                }
                return $this->redirect($this->generateUrl("common_library_evaluation_index", array()));
            }
        }

        return $this->render('CommonLibraryBundle:Evaluation:edit.html.twig', array(
            'form' => $form->createView(),
            'idEvaluation' => $idEvaluation
        ));
    }

    /**
     * @Route("/{idEvaluation}/delete", options={"expose"=true})
     */
    public function deleteAction($idEvaluation)
    {
        $evaluation = $this->getEvaluationRepository()->find($idEvaluation);
        $em = $this->getDoctrine()->getManager();

        $em->remove($evaluation);
        $em->flush();
        $this->get('session')->getFlashBag()->add('success', 'Evaluation supprimée');
        return $this->redirect($this->generateUrl("common_library_evaluation_index", array()));

    }


    /**
     * @return \Common\Bundle\LibraryBundle\Entity\Repository\EvaluationRepository
     */
    protected function getEvaluationRepository() {
        return $this->getDoctrine()->getRepository('CommonLibraryBundle:Evaluation');
    }

} 